////////////////////////////////////////////////////游记////////////////////////////////////
const config = require('../config');

module.exports = function (app, query, jwt) {
 
  //SELECT * FROM articles WHERE id >= (SELECT id FROM articles WHERE category_id = 123 ORDER BY id LIMIT 10000, 1) LIMIT 10 
  //获取游记列表
  app.get('/travelarticleList', jwt({ secret: config.secret, credentialsRequired: false }), function (req, res, next) {
    let { tag, self, pageSize, current, state } = req.query;
    current = Number(current);
    pageSize = Number(pageSize);
    state = Number(state) ? Number(state) : 0;
    let { userId } = req.user;
    if (pageSize === NaN) {
      pageSize = 10
    }
    if (current === NaN) {
      current = 1
    }
    let sql = `select * from article`;

    let params = [`state=${state}`];
    if (self === 'true') {
      params.push(`author_id=${userId}`)
    }
    if (!!tag) {
      params.push(`class_tag='${tag}'`)
    }
    sql += ` where ` + params.join(' and ');
    sql += ` limit ${pageSize * (current - 1)},${pageSize};SELECT FOUND_ROWS();`;
    console.log(sql)
    query(sql, function (err, rows, fields) {
      if (err) {
        const json = {
          code: false,
          message: err.message
        };
        console.log(json);
        res.json(json);
      } else {
        console.log(rows)
        if (rows[1] && rows[1].length > 0) {
          let list = Array.from(rows[0]);
          const data = {
            current,
            pageSize,
            total: rows[1][0]['FOUND_ROWS()'],
            list
          }
          const json = {
            code: true,
            message: '查询成功',
            data
          };
          console.log(json);
          res.json(json);
        }
      }
    });
  });
};
